const Router = require('koa-router')
const router = new Router();
const { returnMsg, queryFn, jwtVerify } = require("../../config")
const moment = require('moment')

// 获取小编列表
router.get("/list",async ctx =>{
    let token = ctx.request.headers['cms-token']
    if(!jwtVerify(token)){
        ctx.body = returnMsg(2, '查询用户信息失败', "token过期或者该用户不存在")
        return
    }   
    let sql =   `select avatar,editable,id,username,player from user where player = 'normal'`
    let result = await queryFn(sql)
    ctx.body = returnMsg(0,'列表请求成功',result)
})

router.get("/adminList",async ctx =>{
    let token = ctx.request.headers['cms-token']
    if(!jwtVerify(token)){
        ctx.body = returnMsg(2, '查询用户信息失败', "token过期或者该用户不存在")
        return
    }   
    let sql =   `select avatar,editable,id,username,player from user where player = 'normal' or player = 'vip'`
    let result = await queryFn(sql)
    ctx.body = returnMsg(0,'列表请求成功',result)
})

// 修改编辑权限
router.post("/update",async ctx =>{
    let token = ctx.request.headers['cms-token']
    if(!jwtVerify(token)){
        ctx.body = returnMsg(2, '查询用户信息失败', "token过期或者该用户不存在")
        return
    }   
    /* 开头编辑权限，open：1 关闭2 */
    let {id, open} = ctx.request.body;
    if(!id || (open!=0 && open!=1)){
        ctx.body = returnMsg(1,'参数错误')
        return
    }

    let sql = `select editable from user where id = ${id}`
    let result = await queryFn(sql)
    console.log(result[0].editable, open)
    if(result[0].editable == 1 && open === 1){
        ctx.body = returnMsg(2,'该用户已有编辑权限')
        return
    }
    if(result[0].editable == 0 && open === 0){
        ctx.body = returnMsg(2,'该用户未有编辑权限')
        return
    }
    // 修改用户的编辑权限
    let sql2 = `update user set editable = ${open} where id = ${id}`
     await queryFn(sql2)
    ctx.body = returnMsg(0,'用户编辑权限修改成功')
})

// 修改管理员权限
router.post("/adimnUpdate",async ctx =>{
    let token = ctx.request.headers['cms-token']
    if(!jwtVerify(token)){
        ctx.body = returnMsg(2, '查询用户信息失败', "token过期或者该用户不存在")
        return
    }   
    /* 开头编辑权限，open：1 关闭2 */
    let {id, open} = ctx.request.body;
    if(!id || (open!=0 && open!=1)){
        ctx.body = returnMsg(1,'参数错误')
        return
    }
    let sql3 = `select player from user where token = '${token}'`
    console.log(sql3)
    let result3 = await queryFn(sql3)
    if(result3[0].player != 'admin'){
        ctx.body = returnMsg(2,'只有超级管理员才有编辑权限')
        return
    }

    let sql = `select player from user where id = ${id}`
    let result = await queryFn(sql)
    if(result[0].player == 'vip' && open === 1){
        ctx.body = returnMsg(2,'该用户已有管理员权限')
        return
    }
    if(result[0].player == 'normal' && open === 0){
        ctx.body = returnMsg(2,'该用户未有管理员权限')
        return
    }
    // 修改用户的编辑权限
    let sql2 = `update user set player = '${open==1?'vip':'normal'}' where id = ${id}`
     await queryFn(sql2)
    ctx.body = returnMsg(0,'用户管理员权限修改成功')
})

module.exports = router